//index.js
//获取应用实例
const app = getApp()
var common = require('../../utils/common.js');
var zhmd5 = require('../../utils/zhmd5.js')
var isChoiceness = true;
var page = 1;
var research = false
Page({
  data: {
    winWidth: 0,
    winHeight: 0,
    clipboard: '',
    cbitem: [],
    cbsw: false,
    isFind: false,
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    // tab切换  
    currentTab: 0,
    items:[],
    todayitems:[],
    skitems:[],
    hotitems:[],
    sptodayitems:[],
    favimg:{
      imgUrl: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/ico5.png',
      curUrl: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/ico5hover.png',
    },
    sessionId: app.globalData.sessionId,
    searchKeyword: '',  //需要搜索的字符  
    searchSongList: [], //放置返回数据的数组  
    isFromSearch: true,   // 用于判断searchSongList数组是不是空数组，默认true，空的数组  
    searchPageNum: 1,   // 设置加载的第几次，默认是第一次  
    todayPageNum: 1,
    skPageNum: 1,
    callbackcount: 15,      //返回数据的个数  
    searchLoading: true, //"上拉加载"的变量，默认false，隐藏  
    toadysearchLoading: true,
    sksearchLoading: true,
    searchLoadingComplete: false,  //“没有数据”的变量，默认false，隐藏
    isIphoneX: false,
    onlyWx: false,
    statusBarHeight: app.globalData.statusBarHeight,
    firstuser: false,
    detailedtc: false,
    sharetc: false,
    sharepic: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc2.png',
    sharenpic: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc6.png',
    shareData: [],
    news: app.globalData.newnotice,
    oldsharetc: false,
    oldsharepic: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc3.png',
    sharesucctc: false,
    sharesucc: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharesuccess.png',
    sharesuccData:[],
    socketMessage: [],
    formId: '',
    socketMessagesw: false,
    sharepictc: false,
    shareimg: '',
    loading: true,
    sharentc: false,
    hasUnfinished: false,
    freeId: '',
    isSpreader: false,
    spreadertc: false,
    imgpath: '',
    spreadertitle: '',
    channel: '',
    qrcode: '',
    qrcodetc: false,
    shareEnable: false,
    firstuserstep1: true,
    firstuserstep2: false,
    classification: [],
    seachitems:[],
    page: 1,
    userInfo: [],
    logined: false,
    jxpage:1,
    hotItemKey:[
      {
        name:"高佣爆品",
        path:"/app/v2/goods/specialGoods"
      },
      {
        name:"限时免单",
        path:"/app/v2/goods/freeShipping99"
      },
      {
        name:"正在热卖",
        path:"/app/goods/hot"
      },
    ],
    currentNav: 0,
    promoteNav:[
      {
        name: "新手指引",
        img: "/img/new/newpel@3x.png",
        path: "/pages/help1/help1?tab=0",
        width: '12px',
        height: '13px'
      },
      {
        name: "用户规范",
        img: "/img/new/guide@3x.png",
        path: "/pages/help2/help2",
        width: '12px',
        height: '12px'
      },
      {
        name: "常见问题",
        img: "/img/new/question@3x.png",
        path: "/pages/help1/help1?tab=2",
        width: '12px',
        height: '12px'
      }
    ],
    hotnineitems:[],
    showitems:[],
    highItems:[],
    hotloading: true,
    fixed: false,
    tabtop: 0,
    itemloading: true,
    todayloading: true,
    nineloading: true,
    seachloading: true,
    rToolsShow: false,
    topTabcon: [
      {
        name: '热门'
      },
      {
        name: '京东优品'
      },
      {
        name: '每日新品'
      },
    ],
    topTab: 0,
    nineitems:[],
    itemlist1:[],
    itemlist2:[],
    itemlist3:[],
    newTabNav:[
      {
        title1: '京东自营',
        title2: '品质保证',
        path: '/app/v2/goods/specialGoods',
        type: 110
      },
      {
        title1: '正在秒杀',
        title2: '10点场',
        path: '/app/v2/goods/specialGoods',
        type: 33
      },
      {
        title1: '品牌精选',
        title2: '优质好货',
        path: '/app/v2/goods/specialGoods',
        type: 32
      },
      {
        title1: '九块九',
        title2: '快来抢',
        path: '/app/v2/goods/specialGoods',
        type: 10
      },
    ],
    newTabCurrent: 0,
    spItem:[],
    spPath: '/app/v2/goods/specialGoods',
    spType: '110',
    sploading: true,
    brand: [],
    sppage: 1,
    swTab: [
      {
        title: '高佣爆品',
        path: '/app/v2/goods/specialGoods',
        type: 140,
        itemList:[]
      },
      {
        title: '大家都在推',
        path: '/app/v2/goods/specialGoods',
        type: 150,
        itemList:[]
      },
      {
        title: '推手精选',
        path: '/app/v2/goods/specialGoods',
        type: 23,
        itemList:[]
      },
    ],
    opacityid: 0
  },
  onShareAppMessage: function (res) {
    var path = 'pages/index/index?userId=' + app.globalData.userId
    var imageUrl = 'https://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharepic.jpg'
    app.globalData.newnotice = true
    this.setData({
      news: app.globalData.newnotice
    });
    var title = '京多多'
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res)
      if (app.globalData.userInfo.hasShop){
        fromOf = '&fO=fsk'
      }else{
        fromOf = '&fO=fod'
      }
      if(res.target.dataset.item.is99){
        title = '快帮帮我，就差你一个了'
      }else{
        title = app.globalData.userInfo.nickname + '分享给你一个超值特价商品，快来看看吧'
      }
      console.log('/pages/itemdetail/itemdetail?userId=' + app.globalData.userId + '&sku=' + res.target.dataset.item.skuId + fromOf)
      path = '/pages/itemdetail/itemdetail?userId=' + app.globalData.userId + '&sku=' + res.target.dataset.item.skuId + fromOf
      imageUrl = res.target.dataset.item.image
    }
    return {
      title: title,
      path: path,
      imageUrl: imageUrl
    }
  },
  onLoad: function (res) {
    this.getshowitems('/app/v2/goods/freeShipping99')
    this.getBrandList()
    this.getlbpicdata()
    let d = new Date();
    let thisH = d.getHours()
    this.data.newTabNav[1].title2 = thisH + '点场'
    this.setData({
      newTabNav: this.data.newTabNav
    })
    this.firstuserstep1()
    console.log(res)
    if (res && res.active){
        this.setData({
          firstuser: false,
          currentTab: 2
        })
    }
    if (app.globalData.sessionId !== undefined) {
      this.setData({
        logined: true,
        userInfo: app.globalData.userInfo
      })
    }
    if (app.globalData.channel) {
      this.setData({
        firstuser: true,
        currentTab: 2
      })
    }
    var that = this;
    wx.getStorage({
      key: 'hotitems',
      success: function (res) {
        console.log(res.data)
        that.setData({
          hotitems: res.data
        })
      }
    })
    this.getclassificationdata()
    that.setData({
      news: app.globalData.newnotice,
      isSpreader: app.globalData.spreader
    });
    // wx.connectSocket({
    //   url: 'wss://miniapp.meyoutao.com/ws/buyer',
    // })
    // wx.onSocketOpen(function (res) {
    //   console.log('WebSocket连接已打开！')
    // })
    // wx.onSocketError(function (res) {
    //   console.log('WebSocket连接打开失败，请检查！')
    // })
    // wx.onSocketMessage(function (res) {
    //   console.log('收到服务器内容：' + res.data)
    //   var str = JSON.parse(res.data)
    //   console.log(str)
    //   that.setData({
    //     socketMessage: str,
    //     socketMessagesw: true
    //   });
    //   setTimeout(function(){
    //     that.setData({
    //       socketMessagesw: false
    //     });
    //   },5000)
    // })
    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    wx.getStorage({
      key: 'classification',
      success: function (res) {
        console.log(res.data)

      },
      fail: function (res) {
        console.log(res.data)
        const requestTask = wx.request({
          method: "POST",
          header: { "content-type": "application/x-www-form-urlencoded" },
          data: {

          },
          url: app.globalData.url + "/app/v2/goods/categorys",
          async: true,
          timeout: 10000,
          success: function (data) {
            console.log(data)
            wx.setStorage({
              key: "classification",
              data: data.data
            })

          },
          error: function (textStatus) {
            console.error(textStatus);
          },
          complete: function (XMLHttpRequest, status) {
            if (status == 'timeout') {
              requestTask.abort()    // 超时后中断请求
              wx.showModal({
                title: '提示',
                content: '网络超时，请重试',
                showCancel: 'false',
                success: function (res) {
                  if (res.confirm) {
                    wx.redirectTo({
                      url: '/pages/index/index'
                    })
                  }
                }
              })
            }
          }
        })
      }
    })
    // wx.getStorage({
    //   key: 'share',
    //   success: function (res) {
    //     console.log(res.data)
    //     if (!res.data){
    //       that.setData({
    //         oldsharetc: true
    //       })
    //     }
    //   }
    // })
    wx.getStorage({
      key: 'firstuser',
      success: function (res) {
        console.log(res.data)
      },
      fail: function () {
        that.setData({
          firstuser: true,
        });
        wx.setStorage({
          key: "firstuser",
          data: false
        })
        console.log(that.data.sharesuccData)
      }
    })
    let isIphoneX = app.globalData.isIphoneX;
    this.setData({
      isIphoneX: isIphoneX,
      shareEnable: app.globalData.shareEnable
    })
    console.log('shareEnable:' + app.globalData.shareEnable)
    this.getitemdata()
    // this.gethotdata()
    this.getlbpicdata()
    this.get99ordsuc()
    this.hasUnfinished()
    this.getnineitemdata()
    this.getSpItem(this.data.newTabNav[0].path,this.data.newTabNav[0].type)
    this.getSpecialGoods()
    this.getAllBuyItem()
    this.getFeaturedItem()
    this.getOpacityItem()
  },
  gettabnav(){
    console.log('sessionId:',app.globalData.sessionId)
    if (app.globalData.sessionId !== undefined) {
      this.setData({
        logined: true,
        userInfo: app.globalData.userInfo
      })
      console.log('用户信息')
      console.log(app.globalData.userInfo )
      
      this.setBottomNav()
    } else {
      this.setData({
        logined: false,
        hotItemKey:[
          {
            name:"限时免单",
            path:"/app/v2/goods/freeShipping99"
          },
          {
            name:"正在热卖",
            path:"/app/goods/hot"
          },
        ],
      })
      this.getshowitems(this.data.hotItemKey[0].path)
      // this.loginTip()
    }
  },
  getDomHeight(){
    let query = wx.createSelectorQuery()
    query.select('.newTabNav').boundingClientRect( (rect) => {
      console.log(rect)
      this.setData({
        tabtop: rect.top - rect.height
      })
      app.globalData.tabtop = rect.top - rect.height
    }).exec()
  },
  onShow: function () {
    var that = this;
    if (app.globalData.sessionId !== undefined) {
      this.setData({
        logined: true,
        userInfo: app.globalData.userInfo
      })
    }
    if(app.globalData.tabtop == ''){
      this.getDomHeight()
    }else{
      this.setData({
        tabtop: app.globalData.tabtop
      })
    }
    this.setData({
      userInfo: app.globalData.userInfo
    })
    // this.gettabnav()
    console.log(this.data.userInfo)
    wx.getClipboardData({
      success: function (res) {
        console.log('res.data:' + res.data)
        console.log('app.globalData.clipboard:' + app.globalData.clipboard)
        var str = res.data;
        var urlnew = res.data.split("?")[0]
        var urlold = app.globalData.clipboard.split("?")[0]
        console.log(urlold, urlnew)
        if (str.indexOf("jd.com") != -1) {
          if (urlold !== urlnew) {
            console.log(1)
            app.globalData.clipboard = res.data
            that.getclipboarddata(res.data)
            console.log('app.globalData.clipboard:' + app.globalData.clipboard)
          } else if (str.match(".*[0-9]{6,18}.*")) {
            console.log(res.data, app.globalData.clipboard)
            if (res.data !== app.globalData.clipboard) {
              console.log(2)
              app.globalData.clipboard = res.data
              console.log('app.globalData.clipboard:' + app.globalData.clipboard)
              that.getclipboarddata(res.data)
            }
          }
        }
      }
    })
  },
  setBottomNav() {
    if(app.globalData.userInfo !== null && app.globalData.userInfo.hasShop){
      this.setData({
        hotItemKey:[
          {
            name:"高佣爆品",
            path:"/app/v2/goods/specialGoods"
          },
          {
            name:"限时免单",
            path:"/app/v2/goods/freeShipping99"
          },
          {
            name:"正在热卖",
            path:"/app/goods/hot"
          },
        ],
      })
      this.getshowitems(this.data.hotItemKey[0].path)
    }else{
      this.setData({
        hotItemKey:[
          {
            name:"限时免单",
            path:"/app/v2/goods/freeShipping99"
          },
          {
            name:"正在热卖",
            path:"/app/goods/hot"
          },
        ],
      })
      this.getshowitems(this.data.hotItemKey[0].path)
    }
  },
  loginTip() {
    const that = this
    app.globalData.sessionId = undefined
    wx.showModal({
      title: '提示',
      content: '你需要登录，才能享受优惠',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.showLoading({
            title: '登录中...',
          })
          that.runLogin()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  runLogin() {
    let res = app.login(app.globalData.thisshareTicket)
    this.waitLogin()
  },
  waitLogin() {
    const that = this
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (app.globalData.sessionId && app.globalData.userId) {
          clearInterval(timer);
          resolve(app.globalData);
          that.setData({
            logined: true,
            userInfo: app.globalData.userInfo
          })
          console.log(that.data.logined)
          wx.hideLoading()
          that.setBottomNav()
        } else {
          //todo 信息构建中
        }
      }, 250);
    });

  },
  hasUnfinished() {
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId
      },
      url: app.globalData.url + "/app/user/activity/hasUnfinished99",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        if(data.data.code == 0 && data.data.data.length > 0){
          that.setData({
            hasUnfinished: true
           })
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  firstuserstep1(){
    const that = this
    wx.getStorage({
      key: 'firstBanner',
      success (res) {
        console.log(res.data)
        if(res.data){
          that.setData({
            firstuserstep2: res.data
          })
        }
      },
      fail(res){
        console.log(res)
        that.setData({
          firstuserstep2: true
        })
      }
    })
  },
  closetc(){
    this.setData({
      firstuserstep2: false
    })
    wx.setStorage({
      key:"firstBanner",
      data:false
    })
  },
  promotiontc(){
    this.setData({
      spreadertc: true
    })
  },
  getTitle(e){
    var val = e.detail.value;
    this.setData({
      spreadertitle: val
    });
  },
  getdcode(e){
    var that = this
    wx.showLoading({
      title: '生成中',
    })
    console.log(e)
    var scene = 'channel=' + e.currentTarget.dataset.channel
    console.log(scene)
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        scene: scene,
        page: 'pages/index/index',
        sessionId: app.globalData.sessionId,
        width: '300',
        auto_color: 'false',
        line_color: '{"r":"0","g":"0","b":"0"}',
        is_hyaline: 'false'
      },
      url: app.globalData.url + "/wxa/qrcode/getUnlimitQrcode",
      async: true,
      timeout: 10000,
      success: function (data) {
        wx.hideLoading()
        console.log(data.data.qrcodeLink)
        that.setData({
          qrcode: data.data.qrcodeLink,
          qrcodetc: true,
          spreadertc: false
        });
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  getChannel(e){
    var channel = e.detail.value;
    this.setData({
      channel: channel
    });
  },
  chooseimg(){
    var that = this
    wx.chooseImage({
      count: 1, 
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '图片上传中',
        })
        var tempFilePaths = res.tempFilePaths[0]
        wx.getImageInfo({
          src: tempFilePaths,
          success: function (res) {
            that.setData({
              imgpath: res.path
            })
            console.log(that.data.imgpath)
            wx.hideLoading()
          }
        })
      }
    })
  },
  postformid(skuId) {
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId,
        skuId: skuId,
        formId: that.data.formId
      },
      url: app.globalData.url + "/app/v2/goods/getShareLink",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  socketlink(e){
    console.log(e)
    console.log(e.currentTarget.dataset.socketmessage.sku)
    app.globalData.item = e.currentTarget.dataset.socketmessage.sku
    console.log(app.globalData.item)
    if (e.currentTarget.dataset.socketmessage.sku.is99){
      wx.navigateTo({
        url: '/pages/activeitemdetail/activeitemdetail?sku=' + e.currentTarget.dataset.socketmessage.sku.skuId
      })
    }else{
      wx.navigateTo({
        url: '/pages/itemdetailNew/itemdetailNew?sku=' + e.currentTarget.dataset.socketmessage.sku.skuId
      })
    }
  },
  get99ordsuc(){
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId
      },
      url: app.globalData.url + "/app/user/activity/hasSuc99",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        if (data.data.code == 0 && data.data.data.length > 0){
          that.setData({
            freeId: data.data.data[0].freeId
          })
          wx.getStorage({
            key: 'succSku',
            success: function (res) {
              console.log(res.data)
              if (res.data !== data.data.data[0].sku.skuId) {
                that.setData({
                  sharesucctc: true,
                  sharesuccData: data.data.data[0]
                });
                wx.setStorage({
                  key: "succSku",
                  data: data.data.data[0].sku.skuId
                })
                console.log(that.data.sharesuccData)
              }
            },
            fail: function () {
              that.setData({
                sharesucctc: true,
                sharesuccData: data.data.data[0]
              });
              wx.setStorage({
                key: "succSku",
                data: data.data.data[0].sku.skuId
              })
              console.log(that.data.sharesuccData)
            }
          })
          
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  closeotc() {
    this.setData({
      hasUnfinished: false
    });
    // wx.setStorage({
    //   key: "share",
    //   data: false
    // })
  },
  closesptc() {
    this.setData({
      sharepictc: false,
      shareimg:''
    });
  },
  closesprtc() {
    this.setData({
      spreadertc: false
    });
  },
  closeqtc() {
    this.setData({
      qrcodetc: false
    });
  },
  savedcode() {
    var that = this
    console.log(this.data.qrcode)
    wx.getImageInfo({
      src: this.data.qrcode,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.path,
          success(res) {
            console.log(that.data.news)
            wx.showModal({
              title: '提示',
              content: '二维码已经存到您的相册',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                  that.setData({
                    qrcodetc: false
                  });
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }
        })
      }
    })
    
  },
  saveimg(){
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareimg,
      success(res) {
        wx.hideToast()
        app.globalData.newnotice = true
        that.setData({
          news: app.globalData.newnotice
        });
        console.log(that.data.news)
        wx.showModal({
          title: '提示',
          content: '分享图已经存到您的相册',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.setData({
                sharepictc: false,
                shareimg: ''
              });
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  },
  detailelink(){
    this.setData({
      detailedtc: true,
      hasUnfinished: false
    });
  },
  buybtn(e){
    console.log(e)
    app.globalData.item = e.currentTarget.dataset.item
    app.globalData.freeid = ''
    console.log(app.globalData.item)
    wx.navigateTo({
      url: '/pages/itemdetailNew/itemdetailNew?sku=' + e.currentTarget.dataset.item.skuId
    })
  },
  spikebuybtn(e){
    console.log(e)
    wx.navigateTo({
      url: '/pages/spikeItemdetail/spikeItemdetail?sku=' + e.currentTarget.dataset.item.skuId
    })
  },
  getclipboarddata(content) {
    wx.showLoading({
      title: '加载中',
    })
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        content: content
      },
      url: app.globalData.url + "/app/v2/goods/clipboardSpirit",
      async: true,
      timeout: 10000,
      success: function (data) {
        wx.hideLoading()
        console.log(data)
        if (data.data.code == 0) {
          if (data.data.data.isFind){
            that.setData({
              cbitem: data.data.data,
              cbsw: true,
              isFind: true
            });
          }else{
            that.setData({
              cbitem: data.data.data,
              cbsw: true,
              isFind: false
            });
          }
          console.log(that.data.cbitem)
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  close(){
    this.setData({
      cbsw: false
    });
  },
  closedtc() {
    this.setData({
      detailedtc: false
    });
  },
  activelink(e){
    console.log(e.currentTarget.dataset.from)
    if(e.currentTarget.dataset.from === 'free'){
      wx.navigateTo({
        url: '/pages/freeItemList/freeItemList',
        success: function (res) {
          console.log(res)
        }
      })
    }else if(e.currentTarget.dataset.from === 'lvup'){
      wx.switchTab({
        url: '/pages/myStore/myStore',
        success: function (res) {
          console.log(res)
        }
      })
    }
    
  },
  queenlink(){
    wx.navigateTo({
      url: '/pages/active/active',
      success: function (res) {
        console.log(res)
      }
    })
  },
  tiptc(){
    this.setData({
      detailedtc: true
    })
  },
  /** 
     * 滑动切换tab 
     */
  bindChange(e) {
    var that = this;
    this.setData({ 
      currentTab: e.detail.current,
      searchPageNum: 1,
      todayPageNum: 1,
      skPageNum: 1,
      isFromSearch: true,
      searchLoading: true,
      items: [],
      todayitems: [],
      skitems: [],
      nineitems: []
    });
    console.log(e)
    console.log(this.data.searchLoading)
    if (e.detail.current == 0) {
      that.getitemdata()
    }
    if (e.detail.current == 1){
      that.gettodayitemspdata()
      that.gettodayitemdata()
    }
    if (e.detail.current == 2){
      that.getnineitemdata()
    }
  },
  /** 
   * 点击tab切换 
   */
  swichNav(e) {
    console.log(e.currentTarget.dataset.current)
    this.setData({
      loading: true,
      isFromSearch: true,
      searchLoading: true,
    });
    if (this.data.currentTab !== e.currentTarget.dataset.current) {
      this.setData({
        currentTab: e.currentTarget.dataset.current
      })
      if (e.currentTarget.dataset.current == 0) {
        this.getitemdata()
      }
      if (e.currentTarget.dataset.current == 1) {
        this.gettodayitemdata()
      }
      if (e.currentTarget.dataset.current == 2) {
        this.getnineitemdata()
      }
      if (e.currentTarget.dataset.current > 2){
        this.getseitemdata(e.currentTarget.dataset.id)
        this.setData({
          categoryId: e.currentTarget.dataset.id
        })
      }
    }
  },
  topSwichNav(e) {
    console.log(e.currentTarget.dataset.current)
    this.setData({
      loading: true,
    });
    if (this.data.topTab !== e.currentTarget.dataset.current) {
      this.setData({
        topTab: e.currentTarget.dataset.current
      })
      if (e.currentTarget.dataset.current == 0) {
        
      }
      if (e.currentTarget.dataset.current == 1) {
        this.getitemdata()
      }
      if (e.currentTarget.dataset.current == 2) {
        this.gettodayitemdata()
      }
      if (e.currentTarget.dataset.current > 2){
        this.getseitemdata(e.currentTarget.dataset.id)
        this.setData({
          categoryId: e.currentTarget.dataset.id
        })
      }
    }
  },
  getSpecialGoods(){
    const that = this
    common.post({
      url: '/app/v2/goods/specialGoods', data: { pageNo: 1,pageSize:3,type: 140,sessionId: app.globalData.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        that.data.swTab[0].itemList = res.data.data
        console.log(that.data.swTab)
        that.setData({
          swTab: that.data.swTab,
        });
        console.log(that.data.swTab)
      }).catch((res) => {
        console.log(res)
      })
  },
  getAllBuyItem(){
    const that = this
    common.post({
      url: '/app/v2/goods/specialGoods', data: { pageNo: 1,pageSize:3,type: 150,sessionId: app.globalData.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        that.data.swTab[1].itemList = res.data.data
        that.setData({
          swTab: that.data.swTab,
        });
        console.log(that.data.swTab)
      }).catch((res) => {
        console.log(res)
      })
  },
  getOpacityItem(){
    const that = this
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        // console.log(that.data.systemitems)
        if (that.data.swTab[0].itemList.length > 0 && that.data.swTab[1].itemList.length > 0 && that.data.swTab[2].itemList.length > 0) {
          clearInterval(timer);
          resolve(app.globalData);
          console.log('获取数据完成')
          that.setopacity()
        } else {
          //todo 信息构建中
        }
      }, 250);
    });
  },
  setopacity(){
    const that = this
    let timer = setInterval(() => {
      // console.log('begin')
      var opacityid = that.data.opacityid + 1
      if(opacityid < 3){
        that.setData({
          opacityid: opacityid
        })
      }else{
        that.setData({
          opacityid: 0
        })
      }
      // console.log(that.data.opacityid)
    }, 5000);
  },
  getFeaturedItem(){
    const that = this
    common.post({
      url: '/app/v2/goods/specialGoods', data: { pageNo: 1,pageSize:3,type: 23,sessionId: app.globalData.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        that.data.swTab[2].itemList = res.data.data
         that.setData({
          swTab: that.data.swTab,
        });
        console.log(that.data.swTab)
      }).catch((res) => {
        console.log(res)
      })
  },
  getitemdata(){
    const that = this
    common.post({
      url: '/app/v2/goods/list', data: { pageNo: 1,isChoiceness: true,sessionId: app.globalData.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        that.setData({
          items: res.data.data,
        });
        console.log(that.data.items)
      }).catch((res) => {
        console.log(res)
      })
  },
  getitemdatapage(){
    const that = this;
    var page = that.data.jxpage + 1;
    common.post({ url: '/app/v2/goods/list', data: { isChoiceness: true, pageNo: page,sessionId: app.globalData.sessionId } })
      .then((res) => {
        var data = that.data.items;
        console.log(res.data)
        if (that.data.jxpage * 10 < res.data.total) {
          that.setData({
            jxpage: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
          }
          setTimeout(() => {
            console.log(data)
            that.setData({
              items: data,
            })
          }, 300);
        } else {
          console.log('没有了')
          that.setData({
            itemloading: false
          })
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  gettodayitemdata() {
    const that = this
    common.post({
      url: '/app/goods/today', data: { pageNo: 1,sessionId:app.globalData.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        that.setData({
          todayitems: res.data.data,
        });
        console.log(that.data.todayitems)
      }).catch((res) => {
        console.log(res)
      })
  },
  gettodayitemdatapage() {
    const that = this;
    var page = that.data.todayPageNum + 1;
    common.post({ url: '/app/goods/today', data: {pageNo: page,sessionId:app.globalData.sessionId } })
      .then((res) => {
        var data = that.data.items;
        console.log(res.data)
        if (that.data.todayPageNum * 10 < res.data.total) {
          that.setData({
            todayPageNum: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
          }
          setTimeout(() => {
            console.log(data)
            that.setData({
              todayitems: data,
            })
          }, 300);
        } else {
          console.log('没有了')
          that.setData({
            todayloading: false
          })
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  getnineitemdata() {
    const that = this
    isChoiceness = false
    common.post({
      url: '/app/v2/goods/freeShipping99', data: { pageNo: 1,sessionId: app.globalData.sessionId}
    })
      .then((res) => {
        that.setData({
          nineitems: res.data.data,
          loading: false
        });
        console.log(that.data.nineitems)
      }).catch((res) => {
        console.log(res)
      })
  },
  getnineitemdatapage() {
    const that = this;
    var page = that.data.skPageNum + 1;
    common.post({ url: '/app/v2/goods/freeShipping99', data: {pageNo: page,sessionId:app.globalData.sessionId } })
      .then((res) => {
        var data = that.data.nineitems;
        console.log(res.data)
        if (that.data.skPageNum * 10 < res.data.total) {
          that.setData({
            skPageNum: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
          }
          setTimeout(() => {
            console.log(data)
            that.setData({
              nineitems: data,
            })
          }, 300);
        } else {
          console.log('没有了')
          that.setData({
            nineloading: false
          })
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  gethotdata() {
    const that = this
    common.post({
      url: '/app/goods/hot', data: { pageNo: 1, pageSize: 9,sessionId:app.globalData.sessionId}
    })
      .then((res) => {
        var data=[],subdata=[]
        console.log(res.data)
        for(let i=0; i<res.data.data.length; i++){
          let tmp = res.data.data[i];
          subdata.push(tmp)
          console.log(subdata)
          if(i==2){
            data[0] = subdata
            subdata = []
            console.log(data)
          }
          if(i==5){
            data[1] = subdata
            subdata = []
            console.log(data)
          }
          if(i==8){
            data[2] = subdata
            subdata = []
            console.log(data)
          }
        }
        console.log(data)
          that.setData({
            hotitems: data,
            loading: false,
            showitems: data
          });
        wx.setStorage({
          key: "hotitems",
          data: that.data.hotitems
        })
        console.log(that.data.hotitems)
      }).catch((res) => {
        console.log(res)
      })
  },
  favitem(e) {
    var that = this
    console.log(e)
    var edata = e.currentTarget.dataset;
    var i = edata.index
    console.log(edata)
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: { skuId: edata.skuid, sessionId: app.globalData.sessionId},
      url: app.globalData.url + "/app/user/collect",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        if (edata.iscollect) {
          wx.showToast({
            title: '取消收藏',
            icon: "success"
          })
          var currId = edata.skuid;
          if (edata.for == 1){
            var array = that.data.items;
            array[i].isCollect = false;
            array[i].collectTotal = array[i].collectTotal - 1;
            that.setData({
              items: array
            });
          } else if (edata.for == 2){
            var array = that.data.todayitems;
            array[i].isCollect = false;
            array[i].collectTotal = array[i].collectTotal - 1;
            that.setData({
              todayitems: array
            });
          } else if (edata.for == 3) {
            var array = that.data.nineitems;
            array[i].isCollect = false;
            array[i].collectTotal = array[i].collectTotal - 1;
            that.setData({
              nineitems: array
            });
          }
          return false
        } else {
          wx.showToast({
            title: '收藏成功',
            icon: "success"
          })
          var currId = edata.skuid;
          if (edata.for == 1) {
            var array = that.data.items;
            array[i].isCollect = true;
            array[i].collectTotal = array[i].collectTotal + 1;
            that.setData({
              items: array
            });
          } else if (edata.for == 2) {
            var array = that.data.todayitems;
            array[i].isCollect = true;
            array[i].collectTotal = array[i].collectTotal + 1;
            that.setData({
              todayitems: array
            });
          } else if (edata.for == 3) {
            var array = that.data.nineitems;
            array[i].isCollect = true;
            array[i].collectTotal = array[i].collectTotal + 1;
            that.setData({
              nineitems: array
            });
          }
          return false
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  itemlink(e){
    console.log(e)
    var edata = e.currentTarget.dataset
    var that = this
    var content = '<a href="http://www.qq.com" data-miniprogram-appid="appid" data-miniprogram-path="pages/index/index">点击跳小程序</a>'
    var openId = app.globalData.openId
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        skuId: edata.skuid,
        couponId: edata.couponid,
        sessionId: app.globalData.sessionId

      },
      url: app.globalData.url + "/app/goods/wxaSendCoupon",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        wx.request({
          method: "POST",
          header: { "content-type": "application/x-www-form-urlencoded" },
          data: {
            touser: openId,
            msgtype: "text",
            text:
            {
              content: content
            }
          },
          url: 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' + access_token,
          async: true,
          timeout: 10000,
          success: function (res) {
            console.log(res);
          },
          error: function (err) {
            console.log(err);
          }
        });
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  formSubmit(e){
    console.log(e)
    if (e.currentTarget.dataset.item.is99){
      this.setData({
        sharetc: true,
        shareData: e.currentTarget.dataset.item,
        formId: e.detail.formId
      });
    }else{
      this.setData({
        sharentc: true,
        shareData: e.currentTarget.dataset.item,
        formId: e.detail.formId
      });
    }
    console.log(this.data.shareData)
  },
  buyformSubmit(e){
    if (app.globalData.sessionId){
      console.log(e)
      console.log('formId:' + e.detail.formId)
      app.globalData.formId = e.detail.formId
      app.globalData.item = e.currentTarget.dataset.item
      app.globalData.freeid = ''
      console.log(app.globalData.item)
      if (e.currentTarget.dataset.item.is99) {
        wx.navigateTo({
          url: '/pages/freeItemdetail/freeItemdetail?sku=' + e.currentTarget.dataset.item.skuId
        })
      } else {
        console.log('toItemdetail')
        wx.navigateTo({
          url: '/pages/itemdetailNew/itemdetailNew?sku=' + e.currentTarget.dataset.item.skuId
        })
      }
    }else{
      wx.showModal({
        title: '提示',
        content: '你需要登录，才能享受优惠',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            app.login(app.globalData.thisshareTicket)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
    
    
  },
  closestc(){
    this.setData({
      sharetc: false,
      shareData: []
    });
  },
  closentc() {
    this.setData({
      sharentc: false,
      shareData: []
    });
  },
  closesutc(){
    this.setData({
      sharesucctc: false,
      shareData: []
    });
  },
  shareweixinquan(e){
    var that = this
    var edata = e.currentTarget.dataset.item
    this.postformid(e.currentTarget.dataset.item.skuId)
    wx.showToast({
      title: '生成中...',
      icon: 'loading',
      duration: 2000
    });
    console.log(e)
    var imgbgsrc
    if (edata.is99){
      imgbgsrc = '/img/picbg3.jpg'
    }else{
      imgbgsrc = '/img/picbg.jpg'
    }
    console.log(imgbgsrc)
    function sharepic(data,link){
      console.log(data)
      if (data.data.code == 0) {
        var str = edata.title;
        str = str.slice(0, 30)
        var str1 = str.slice(0, 16)
        var str2 = str.slice(17, 30) + '...'
        var format = function (value) {
          var html, _val;
          value = Number(value).toFixed(2);
          if (value == 0) {
            value = 0;
            return html = "<text>0</text>";
          } else {
            value = Number(value).toFixed(2);
          }
          _val = value.split('.');
          return html = _val[0] + '.' + _val[1];
        }
        var price1 = format(edata.price)
        if (edata.coupons) {
          var price2 = format(edata.price - edata.coupons[0].discount)
          var reduce = '券后立省' + edata.coupons[0].discount + '元'
        } else {
          var price2 = format(edata.price)
          var reduce = '券后立省' + 0 + '元'
        }
        wx.getImageInfo({
          src: edata.image,
          success: function (res) {
            console.log(res)
            const sharepic = wx.createCanvasContext('myCanvas')
            var itemimg = res.path
            wx.getImageInfo({
              src: link,
              success: function (res) {
                console.log(res)
                var dcode = res.path
                sharepic.drawImage(imgbgsrc, 0, 0, 1080, 1920)
                sharepic.setFontSize(46)
                sharepic.setTextAlign('center')
                sharepic.setFillStyle('#404142')
                sharepic.fillText(str1, 540, 1013)
                sharepic.fillText(str2, 540, 1083)
                if (edata.tags.length > 0) {
                  sharepic.rect(462, 1137, 164, 54)
                  sharepic.setFillStyle('#ff4564')
                  sharepic.fill()
                  sharepic.setFontSize(35)
                  sharepic.setTextAlign('center')
                  sharepic.setFillStyle('white')
                  sharepic.fillText(edata.tags, 544, 1178)
                }
                sharepic.setFontSize(60)
                sharepic.setTextAlign('center')
                sharepic.setFillStyle('#aaabad')
                sharepic.fillText(price1, 335, 1376)
                sharepic.setFillStyle('#ff4564')
                sharepic.fillText(price2, 750, 1376)
                sharepic.setFontSize(46)
                sharepic.fillText(reduce, 540, 1486)
                sharepic.drawImage(itemimg, 297, 454, 486, 486)
                if (edata.is99) {
                  sharepic.drawImage('/img/freeico.png', 760, 422, 243, 221)
                }
                sharepic.drawImage(dcode, 808, 1646, 236, 236)
                setTimeout(function () {
                  sharepic.draw()
                }, 100)
                setTimeout(function () {
                  wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: 1080,
                    height: 1920,
                    destWidth: 1080,
                    destHeight: 1920,
                    canvasId: 'myCanvas',
                    success: function (res) {
                      console.log(res.tempFilePath)
                      // wx.previewImage({
                      //   current: res.tempFilePath,
                      //   urls: [res.tempFilePath]
                      // })
                      that.setData({
                        sharepictc: true,
                        shareimg: res.tempFilePath,
                        sharetc: false
                      });
                    }
                  })
                }, 1000)
              }
            })
          }
        })
      } else {
        wx.redirectTo({
          url: '/pages/index/index'
        })
      }
    }
    var scene = '?userid=' + getApp().globalData.userId + '&sku=' + e.currentTarget.dataset.item.skuId
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        scene: scene,
        page: 'pages/index/index',
        sessionId: app.globalData.sessionId,
        width: '236',
        auto_color: 'false',
        line_color: '{"r":"0","g":"0","b":"0"}',
        is_hyaline: 'false'
      },
      url: app.globalData.url + "/wxa/qrcode/getUnlimitQrcode",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data.data.qrcodeLink)
        sharepic(data, data.data.qrcodeLink)
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
    
  },
  fetchSearchList: function (e) {
    console.log(e)
    var that = this;
    var searchPageNum = that.data.searchPageNum,//把第几次加载次数作为参数  
        callbackcount = that.data.callbackcount; //返回数据的个数
    if (research){
      isChoiceness = false
    }else{
      isChoiceness = true
    }
    console.log(research)
    if(e == 1){
      const requestTask = wx.request({
        method: "POST",
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          pageNo: that.data.searchPageNum,
          isChoiceness: isChoiceness,
          sessionId: app.globalData.sessionId,
          // onlyWx: that.data.onlyWx
        },
        url: app.globalData.url + "/app/v2/goods/list",
        async: true,
        timeout: 10000,
        success: function (data) {
          console.log(data)
          console.log(that.data.searchPageNum)
          var num = 10 * (that.data.searchPageNum - 1)
          if (data.data.total > num) {
            var items = that.data.items.concat(data.data.data)
            console.log(items)
            setTimeout(function(){
              that.setData({
                items: items, //获取数据数组  
                searchLoading: true,   //把"上拉加载"的变量设为false，显示
                loading: false
              });
              console.log(that.data.items)
            },300)
            
          } else {
            that.setData({
              searchPageNum: 1
            });
            console.log(research)
            if (research){
              that.setData({
                searchLoading: false,  //把"上拉加载"的变量设为false，隐藏
                loading: false
              });
              wx.showToast({
                title: '没有更多商品了',
                icon: 'none',
                duration: 2000
              });
              research = false
            }else{
              const requestTask = wx.request({
                method: "POST",
                header: { "content-type": "application/x-www-form-urlencoded" },
                data: {
                  pageNo: that.data.searchPageNum,
                  isChoiceness: false,
                  sessionId: app.globalData.sessionId,
                  // onlyWx: that.data.onlyWx
                },
                url: app.globalData.url + "/app/v2/goods/list",
                async: true,
                timeout: 10000,
                success: function (data) {
                  research = true
                  console.log(data)
                  console.log(research)
                  console.log(that.data.searchPageNum)
                  var num = 10 * (that.data.searchPageNum - 1)
                  if (data.data.total > num) {
                    var items = that.data.items.concat(data.data.data)
                    console.log(items)
                    that.setData({
                      items: items, //获取数据数组  
                      searchLoading: true,   //把"上拉加载"的变量设为false，显示
                      loading: false
                    });
                    console.log(that.data.items)
                  } else {
                    that.setData({
                      searchLoading: false,  //把"上拉加载"的变量设为false，隐藏
                      loading: false
                    });
                    wx.showToast({
                      title: '没有更多商品了',
                      icon: 'none',
                      duration: 2000
                    });
                  }
                },
                error: function (textStatus) {
                  console.error(textStatus);
                },
                complete: function (XMLHttpRequest, status) {
                  if (status == 'timeout') {
                    requestTask.abort()    // 超时后中断请求
                    wx.showModal({
                      title: '提示',
                      content: '网络超时，请重试',
                      showCancel: 'false',
                      success: function (res) {
                        if (res.confirm) {
                          wx.redirectTo({
                            url: '/pages/index/index'
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
            
          }
        },
        error: function (textStatus) {
          console.error(textStatus);
        },
        complete: function (XMLHttpRequest, status) {
          if (status == 'timeout') {
            requestTask.abort()    // 超时后中断请求
            wx.showModal({
              title: '提示',
              content: '网络超时，请重试',
              showCancel: 'false',
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/index/index'
                  })
                }
              }
            })
          }
        }
      })
    }else if(e == 2){
      const requestTask = wx.request({
        method: "POST",
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          pageNo: that.data.todayPageNum,
          isChoiceness: false,
          sessionId: app.globalData.sessionId
        },
        url: app.globalData.url + "/app/goods/today",
        async: true,
        timeout: 10000,
        success: function (data) {
          console.log(data)
          var num = 10 * that.data.todayPageNum
          if (data.data.total > num) {
            var items = that.data.todayitems.concat(data.data.data)
            // that.setData({
            //   todayitems: items, //获取数据数组  
            //   toadysearchLoading: true,   //把"上拉加载"的变量设为false，显示
            //   loading: false
            // });
            setTimeout(function () {
              that.setData({
                todayitems: items, //获取数据数组  
                toadysearchLoading: true,   //把"上拉加载"的变量设为false，显示
                loading: false
              });
              console.log(that.data.items)
            }, 300)
            console.log(that.data.items)
          } else {
            that.setData({
              toadysearchLoading: false,  //把"上拉加载"的变量设为false，隐藏
              loading: false
            });
            wx.showToast({
              title: '没有更多商品了',
              icon: 'none',
              duration: 2000
            });
          }
        },
        error: function (textStatus) {
          console.error(textStatus);
        },
        complete: function (XMLHttpRequest, status) {
          if (status == 'timeout') {
            requestTask.abort()    // 超时后中断请求
            wx.showModal({
              title: '提示',
              content: '网络超时，请重试',
              showCancel: 'false',
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/index/index'
                  })
                }
              }
            })
          }
        }
      })
    }else if(e == 3){
      const requestTask = wx.request({
        method: "POST",
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          pageNo: that.data.skPageNum,
          // onlyWx: that.data.onlyWx
        },
        url: app.globalData.url + "/app/v2/goods/freeShipping99",
        async: true,
        timeout: 10000,
        success: function (data) {
          console.log(data)
          console.log(data.data.total, that.data.skPageNum)
          var num = 10 * that.data.skPageNum
          if (data.data.total > that.data.nineitems.length) {
            var items = that.data.nineitems.concat(data.data.data)
            // that.setData({
            //   nineitems: items, //获取数据数组  
            //   sksearchLoading: true,   //把"上拉加载"的变量设为false，显示
            //   loading: false
            // });
            // console.log(that.data.nineitems)
            setTimeout(function () {
              that.setData({
                nineitems: items, //获取数据数组  
                sksearchLoading: true,   //把"上拉加载"的变量设为false，显示
                loading: false
              });
              console.log(that.data.nineitems)
            }, 300)
          } else {
            that.setData({
              toadysearchLoading: false,  //把"上拉加载"的变量设为false，隐藏
              loading: false
            });
            wx.showToast({
              title: '没有更多商品了',
              icon: 'none',
              duration: 2000
            });
          }
        },
        error: function (textStatus) {
          console.error(textStatus);
        },
        complete: function (XMLHttpRequest, status) {
          if (status == 'timeout') {
            requestTask.abort()    // 超时后中断请求
            wx.showModal({
              title: '提示',
              content: '网络超时，请重试',
              showCancel: 'false',
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/index/index'
                  })
                }
              }
            })
          }
        }
      })
    }else{
      this.getseitemdatapage(this.data.categoryId)
    }
  }, 
  searchScrollLower: function (e) {
    console.log(e)
    var that = this;
    that.setData({
      loading: true
    });
    if (that.data.searchLoading && !that.data.searchLoadingComplete) {
      that.setData({
        searchPageNum: that.data.searchPageNum + 1,
        todayPageNum: that.data.todayPageNum + 1,
        skPageNum: that.data.skPageNum + 1,
        isFromSearch: false  //触发到上拉事件，把isFromSearch设为为false  
      });
      that.fetchSearchList(e.currentTarget.dataset.hot);
    }else{
      console.log(that.data.searchLoading, that.data.searchLoadingComplete)
    }
  },
  onPullDownRefresh: function () {
    var that = this;
    console.log("下拉刷新....")
    that.setData({
      searchPageNum: 1,
      todayPageNum: 1,
      skPageNum: 1,
      isFromSearch: true
    });
    that.onLoad()
    wx.stopPullDownRefresh()
  },
  usercenter: function() {
    app.globalData.newnotice = false
    wx.navigateTo({
      url: '/pages/usercenter/usercenter'
    })
  },
  seachlink: function () {
    wx.navigateTo({
      url: '/pages/seach/seach'
    })
  },
  getlbpicdata: function(){
    const that = this
    common.post({
      url: '/app/banner/list', data: {position: 1,}
    })
      .then((res) => {
        console.log(res.data)
        that.setData({
          imgUrls: res.data.data
        });
        console.log(that.data.imgUrls)
        
      }).catch((res) => {
        console.log(res)
      })
  },
  imglink: function (link) {
    wx.redirectTo({
      url: link
    })
  },
  getclassificationdata() {
    const that = this
    wx.getStorage({
      key: 'classification',
      success: function (res) {
        console.log(res.data)
        that.setData({
          classification: res.data,
        });
        if(that.data.from == 'free'){
          that.getnineitemdata()
          that.setData({
            currentTab: 2
          })
        }else{
          that.getitemdata(res.data[0].id)
        }
      },
      fail: function (res) {
        console.log(res.data)
        common.post({
          url: '/app/v2/goods/categorys', data: {}
        })
          .then((res) => {
            console.log(res.data)
            that.setData({
              classification: res.data,
            });
            wx.setStorage({
              key: "classification",
              data: res.data
            })
            if(that.data.from == 'free'){
              that.getnineitemdata()
              that.setData({
                currentTab: 2
              })
            }else{
              that.getitemdata(res.data[0].id)
            }
            
          }).catch((res) => {
            console.log(res)
          })
      }
    })
  },
  getseitemdata(categoryId) {
    const that = this
    this.setData({
      seachitems: [],
      categoryId: categoryId
    });
    common.post({
      url: '/app/v2/goods/list', data: { categoryId: categoryId, onlyWx: this.data.onlyWx, pageNo: 1 }
    })
      .then((res) => {
        console.log(res.data)
        that.setData({
          seachitems: res.data.data,
          loading: false,
          itemIsShow: true
        });
      }).catch((res) => {
        console.log(res)
      })
  },
  getseitemdatapage(categoryId) {
    const that = this;
    var page = that.data.page + 1;
    common.post({ url: '/app/v2/goods/list', data: { categoryId: categoryId, onlyWx: this.data.onlyWx, pageNo: page } })
      .then((res) => {
        var data = that.data.seachitems;
        console.log(res.data)
        if (that.data.page * 10 < res.data.total) {
          that.setData({
            page: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
            setTimeout(function () {
              that.setData({
                seachitems: data
              });
              console.log(data)
            }, 300)
          }
        } else {
          console.log('没有了')
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  toHelp1(){
    wx.navigateTo({
      url: '/pages/help1/help1',
      success: function (res) {
        console.log('toHelp1')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toHelp2() {
    wx.navigateTo({
      url: '/pages/help2/help2',
      success: function (res) {
        console.log('toHelp2')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toMyStone(){
    wx.switchTab({
      url: '/pages/myStore/myStore',
      success: function (res) {
        console.log('toMyStore')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toPath(e){
    console.log(e)
    wx.navigateTo({
      url: e.currentTarget.dataset.path,
      success: function (res) {
        console.log('to' + e.currentTarget.dataset.path)
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  navChange(e){
    console.log(e.currentTarget.dataset.path)
    if(this.data.currentNav == e.currentTarget.dataset.idx){

    }else{
      this.setData({
        currentNav: e.currentTarget.dataset.idx,
        showitems:[],
        hotloading: true
      });
      this.getshowitems(e.currentTarget.dataset.path)
    }
    
  },
  getshowitems(url){
    const that = this
    isChoiceness = false
    common.post({
      url: url, 
      data: { pageNo: that.data.skPageNum, sessionId: app.globalData.sessionId}
    })
      .then((res) => {
        var data=[],subdata=[]
        console.log(res.data)
        for(let i=0; i<res.data.data.length; i++){
          let tmp = res.data.data[i];
          subdata.push(tmp)
          console.log(subdata)
          if(i==2){
            data[0] = subdata
            subdata = []
            console.log(data)
          }
          if(i==5){
            data[1] = subdata
            subdata = []
            console.log(data)
          }
          if(i==8){
            data[2] = subdata
            subdata = []
            console.log(data)
          }
        }
        console.log(data)
          that.setData({
            hotloading: false,
            showitems: data
          });
        console.log(that.data.showitems)
      }).catch((res) => {
        console.log(res)
      })
  },
  onPageScroll: function (e) {
    // console.log(e.scrollTop)
    var scrollHeight = 120
    if(e.scrollTop < scrollHeight){
      var number1 = 1 - e.scrollTop / scrollHeight,
          number2 = e.scrollTop / scrollHeight
      if(number1 > 0 && number2 < 1){
        this.setData({
          opacity: number1,
          opacity1: number2
        }) 
      }
    }else{
      if(this.data.opacity !== 0 && this.data.opacity1 !== 1){
        this.setData({
          opacity: 0,
          opacity1: 1
        }) 
      }
    }
    // console.log(e.scrollTop,this.data.tabtop)
    if(e.scrollTop >= this.data.tabtop){
      if(!this.data.fixed){
        this.setData({
          fixed: true
        })
      }
    }else{
      if(this.data.fixed){
        this.setData({
          fixed: false
        })
      }
    }
    if(e.scrollTop > 600){
      this.setData({
        rToolsShow: true
      })
    }else{
      this.setData({
        rToolsShow: false
      })
    }
  },
  onReachBottom(){
    console.log('bottom')
    console.log(this.data.currentTab)
    if(this.data.topTab == 0){
      this.getSpItempage(this.data.spPath,this.data.spType)
    }else if(this.data.topTab == 1){
      this.getitemdatapage()
    }else if(this.data.topTab == 2){
      this.gettodayitemdatapage()
    }else if(this.data.topTab == 3){
      this.getnineitemdatapage()
    }else if(this.data.topTab > 3){
      this.getseitemdatapage(this.data.categoryId)
    }
  },
  jlshare(e){
    console.log(e)
    const that = this
    wx.navigateTo({
      url: '/pages/createSolitaire/createSolitaire',
      events: {
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
      success: function (res) {
        console.log('toCreateSolitaire')
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: e.currentTarget.dataset.item })
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  totop(){
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  newNavItemList(e){
    console.log(e)
    let path = e.currentTarget.dataset.path,
        index = e.currentTarget.dataset.index,
        type = e.currentTarget.dataset.type
    this.setData({
      newTabCurrent: index,
      spPath: path,
      spType: type,
      sppage: 1,
      sploading: true
    })
    this.getSpItem(path,type)
  },
  getSpItem(path,type){
    const that = this
    this.setData({
      spItem: [],
      sploading: true
    });
    common.post({
      url: path, data: { type: type,pageNo: 1,sessionId: app.globalData.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        that.setData({
          spItem: res.data.data,
        });
        if(res.data.total == 0){
          that.setData({
            noSpItem: true,
            sploading: false
          })
        }else if(res.data.total < 11){
          that.setData({
            sploading: false,
          });
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getSpItempage(path,type) {
    const that = this;
    var page = that.data.sppage + 1;
    common.post({ url: path, data: { type: type, pageNo: page } })
      .then((res) => {
        var data = that.data.spItem;
        console.log(res.data)
        if (that.data.sppage * 10 < res.data.total) {
          that.setData({
            sppage: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
            setTimeout(function () {
              that.setData({
                spItem: data
              });
              console.log(data)
            }, 300)
          }
        } else {
          console.log('没有了')
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
          that.setData({
            sploading: false,
          });
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  tofreeZone(){
    wx.navigateTo({
      url: '/pages/freeItemList/freeItemList',
      success(res){
        console.log('toFreeItemList')
      },
      fail(res){
        console.log(res)
      }
    })
  },
  toSpItemList(e){
    console.log(e)
    let url = '/pages/spItemList/spItemList?index=' + e.currentTarget.dataset.index
    wx.navigateTo({
      url: url,
      success(res){
        console.log('toFreeItemList')
      },
      fail(res){
        console.log(res)
      }
    })
  },
  getBrandList(){
    const that = this
    common.post({
      url: '/app/v2/goods/hotBrand', data: {sessionId: app.globalData.sessionId}
    })
      .then((res) => {
        console.log(res.data)
        that.setData({
          brand: res.data,
        });
      }).catch((res) => {
        console.log(res)
      })
  },
  toBrandList(e){
    console.log(e)
    wx.navigateTo({
      url: '/pages/brandItemList/brandItemList?brandid=' + e.currentTarget.dataset.id + '&brandname=' + e.currentTarget.dataset.brandname,
      success(res){
        console.log('toBrandItemList')
      },
      fail(res){
        console.log(res)
      }
    })
  }
})  






